import React, {Component, Fragment} from 'react';
import {Button, Card, Table, Image} from 'antd';
import {MinusOutlined, PlusOutlined} from "@ant-design/icons";
import {reqLatestBook} from '../../api/book';
import {dateTimeDateFormat} from "../../utils/tools";
import {Link} from 'react-router-dom';

// 首页
export default class BookLatest extends Component {
  state = {
    list: [],
    totalCount: 0,
    loading: false,
  }
  initColumns = () => {
    this.columns = [
      {
        title: '书名',
        dataIndex: 'title',
        render: (text, record) => <Link to={'/admin/books/list/book/'+record._id}>{text}</Link>
      },
      {
        title: '发布信息',
        dataIndex: 'publish_info',
        ellipsis: true
      },
      {
        title: '类型',
        dataIndex: 'category',
        render: (category) => category === 'fiction' ? '虚构类' : '非虚构类'
      },
      {
        title: '封面',
        dataIndex: 'poster',
        render: (poster) => <Image src={poster} width={60} height={80}/>
      },
      {
        title: '得分',
        dataIndex: 'score'
      },
      {
        title: '下载时间',
        dataIndex: 'download_time',
        render: (download_time) => dateTimeDateFormat(download_time)
      }
    ]
  }

  UNSAFE_componentWillMount() {
    this.initColumns();
  }

  // 获取最新图书
  getLatestBook = async (data = {}) => {
    try {
      this.setState({loading: true})
      const {data: result} = await reqLatestBook(data);
      console.log(result);
      this.setState({list: result.items, totalCount: result.total_count, loading: false});
    } catch (e) {
      console.log(e);
      this.setState({loading: false})
    }
  }
  // 修改
  onChange = (pagination, filters, sorter, extra) => {
    const {current, pageSize} = pagination;
    this.getLatestBook({page: current, page_size: pageSize});
  }

  componentDidMount() {
    this.getLatestBook();
  }

  render() {
    const {list, totalCount, loading} = this.state;
    const extra = (
      <Fragment>
        <Button type='primary' onClick={this.addClick} icon={<PlusOutlined/>} style={{marginRight: '10px'}}>
          添加
        </Button>
        <Button type='primary' danger onClick={this.deleteClick} icon={<MinusOutlined/>}>
          删除
        </Button>
      </Fragment>
    )
    const pagination = {
      defaultPageSize: 10,
      position: ['bottomCenter'],
      showQuickJumper: true,
      total: totalCount,
    }
    return (
      <Card title='最新图书' extra={extra}>
        <Table pagination={pagination}
               onChange={this.onChange}
               scroll={{x: 800}}
               loading={loading}
               columns={this.columns}
               dataSource={list}
               rowKey='_id'/>
      </Card>
    )
  }
}
